/**
 * 
 */
package com.tiance.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2018/8/3
 *
 * Description：
 *
 * Modification History:
 *
 */
public class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    /**
     * 从Json转到的map中获取指定KEY值
     * @param json
     * @param key
     * @return
     */
    public static String getValueFromJsonMap(String json, String key) {
        Map<String, String> map = convertJsonToMap(json);
        return map.get(key);
    }

    /**
     * json转map
     * @param json
     * @return
     */
    public static Map<String, String> convertJsonToMap(String json) {
        Map<String, String> map = new HashMap<String, String>();
        if (StringUtils.isBlank(json)) {
            return map;
        }
        try {
            map = JSON.parseObject(json, new TypeReference<Map<String, String>>() {
            });
        } catch (Exception e) {
            logger.error(MessageFormat.format("{0}：转换Json异常", json), e);
        }
        return map;
    }
    
    public static String objToJson(Object obj) {
        if(obj == null){
            return null;
        }
        return JSON.toJSONString(obj);
    }

    public static void main(String[] args) {
        Map<String, String> a = new HashMap<String, String>();
        a.put("a", "b");
        System.out.println(JSON.toJSONString(a));

        String s = getValueFromJsonMap("{\"a\":\"b\"}", "a");
        System.out.println(s);
    }
}
